#include "DirectoryListing.h"
#include "FileOperations.h"
#include <sys/types.h>

DirectoryListing::DirectoryListing()
{
	
}
DirectoryListing::~DirectoryListing()
{
	// Delete the listing.
	Clear();
}
DirectoryEntry* DirectoryListing::Pop()
{
	DirectoryEntry* item;
	if (Listing.empty())
	{
		return NULL;
	}
	item = Listing.front();
	Listing.pop_front();
	return item;
}
void DirectoryListing::Clear()
{
	DirectoryEntry* deleteMe;
	while (!Listing.empty())
	{
		deleteMe = Listing.front();
		Listing.pop_front();
		delete deleteMe;
	}
}
DirectoryEntry* DirectoryListing::AddFile(const gchar* name, INT64 size, INT64 time_write)
{
	DirectoryEntry* entry;	
	entry = new DirectoryEntry();
	entry->FileName = name;
	//entry->dwFileAttributes = attrib;
	entry->LastWriteTime = time_write;
	entry->nFileSize = size;
	Listing.push_back(entry);
	return entry;
}
void DirectoryListing::ReadDirectory(const gstring &directory)
{	
	Clear();
	FileOperations::ReadDirectory(directory.c_str(), this);
}
void DirectoryListing::CombineFileNames(const gstring& folder, const gstring& fileName, gstring& output)
{
	size_t folderLength = folder.size();
	size_t fileNameLength = fileName.size() + 4;
	size_t length = folderLength + fileNameLength;	
	gchar directorySeparator = FileOperations::DirectorySeparator();
	output.reserve(length + 1);
	output = folder;
	if (folder[folderLength - 1] != directorySeparator)
	{
		output += directorySeparator;
	}
	output += fileName;
}
DirectoryEntry* DirectoryListing::FindFile(const gstring& file)
{
	for (auto& loop : Listing)
	{
		if (loop->FileName == file)
		{
			return loop;
		}
	}
	return NULL;
}
